﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace OT.Common
{
    /// <summary>
    /// 基于数据模型：Stamp, Record Count判断是否表发生改变
    /// 提供缓存数据的管理
    /// 不关注具体的数据获取
    /// </summary>
    public class DataCache 
    {
        #region Instance

        private DataCache() { }

        static DataCache m_DataCache = null;

        static public DataCache Instance()
        {
            if (m_DataCache == null)
                m_DataCache = new DataCache();
            return m_DataCache;
        }

        #endregion

        #region NeedRefresh

        Dictionary<string, long> m_dictStamp = new Dictionary<string, long>();

        public bool NeedRefresh(string table, string key, object objDict)
        {
            long stamp = GetStamp(table);

            bool need = false;

            if (objDict == null || !m_dictStamp.ContainsKey(key) || m_dictStamp[key] != stamp)
            {
                if (m_dictStamp.ContainsKey(key))
                    m_dictStamp[key] = stamp;
                else
                    m_dictStamp.Add(key, stamp);

                need = true;
            }

            return need;
        }

        #endregion

        #region GetStamp

        public Int64 GetStamp(string tableName)
        {
            string sql = string.Format("select top 1 Stamp  from {0} order by Stamp desc", tableName);
            DataTable dt = new DataTable(); // = new BaseDAL().ExecuteDataTable(sql);

            Int64 ret = 0;

            if (dt.Rows.Count > 0)
            {
                byte[] obj = dt.Rows[0]["Stamp"] as byte[];
                string str = "";
                foreach (byte bt in obj)
                {
                    if (bt != 0)
                    {
                        str += Convert.ToString(bt, 16);
                    }
                }

                ret = Convert.ToInt64(str, 16);
            }

            return ret;
        }

        #endregion


    }


}
